#!/usr/bin/python3
"""
Log resource usage info.

To analyze logged data, use profile-analyze tool.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import json
import resource
import signal
import sys
import time

try:
    import subprocess32 as subprocess
except ImportError:
    import subprocess

name = sys.argv[1]
command = sys.argv[2:]

start = time.time()

try:
    status = subprocess.call(command)
except KeyboardInterrupt:
    print("profile: Interrupted")
    sys.exit(128 + signal.SIGINT)

elapsed = time.time() - start

ru = resource.getrusage(resource.RUSAGE_CHILDREN)

# {"maxrss": ru.ru_maxrss, ...}
info = {a[3:]: getattr(ru, a) for a in dir(ru) if a[:3] == "ru_"}

info["command"] = command
info["cpu"] = (ru.ru_utime + ru.ru_stime) / elapsed * 100
info["elapsed"] = elapsed
info["name"] = name
info["start"] = start
info["status"] = status

print("PROFILE " + json.dumps(info, sort_keys=True))

sys.exit(status)
